package com.blb.auth_service.config;

import com.blb.common.utils.ObjectUtils;
import com.blb.common.utils.RsaUtils;
import lombok.Data;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 读取配置文件的配置类 properties，yml
 */
@Data
@Configuration
//读取配置文件的注解
@ConfigurationProperties(prefix = "blb.jwt")
public class JwtProperties {

    private String secret;//秘钥
    private String pubKeyPath;//公钥路径
    private String priKeyPath;//私钥路径
    private String cookieName;//cookie名称
    private Integer expire;//cookie过期时间
    private Integer cookieMaxAge;//cookie生命周期
    private PublicKey publicKey;//公钥
    private PrivateKey privateKey;//私钥

    //在构造方法之后自动执行
    @PostConstruct
    public void init(){
        File pubKey = new File(pubKeyPath);
        File priKey = new File(priKeyPath);
        try {
            //判断公钥和私钥如果不存在就创建
            if (!priKey.exists() || !pubKey.exists()) {
                //创建公钥和私钥文件
                RsaUtils.generateKey(this.pubKeyPath, this.priKeyPath, this.secret);
            }
            //读取公钥和私钥内容
            this.publicKey = RsaUtils.getPublicKey(this.pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(this.priKeyPath);
        }catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
}
